package com.opdar.athena.message.agent.client;

import com.opdar.athena.tcp.TcpRecive;
import com.opdar.athena.utils.JSONUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.ReferenceCountUtil;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.List;

/**
 * Created by shiju on 2017/6/27.
 */
public class ClientEncoder extends MessageToMessageEncoder<Object> {
    private byte[] project;
    private int version;

    public ClientEncoder(byte[] project, int version) {
        this.project = project;
        this.version = version;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, List<Object> list) throws Exception {
        if(o instanceof TcpRecive){
            //项目名称(fixed) 协议版本(int) 消息类型(short int) 长度(int) 消息内容(长度)
            byte[] body;
            if(((TcpRecive) o).getMessage() instanceof String){
                body = ((String) ((TcpRecive) o).getMessage()).getBytes();
            }else if(((TcpRecive) o).getMessage() instanceof byte[]){
                body = (byte[]) ((TcpRecive) o).getMessage();
            }else{
                body = JSONUtil.toJSONAsBytes(((TcpRecive) o).getMessage());
            }
            ByteArrayOutputStream baos = null;
            DataOutputStream outputStream = new DataOutputStream(baos = new ByteArrayOutputStream());
            outputStream.writeInt(version);
            outputStream.writeShort(((TcpRecive) o).getType());
            outputStream.writeInt(body.length);
            list.add(Unpooled.wrappedBuffer(project,baos.toByteArray(),body));
        }
    }
}
